import React, { useState, useEffect, useRef } from "react";
import {
  SearchBar,
  Card,
  Tabs,
  Toast,
  SpinLoading,
  Button,
  Swiper,
} from "antd-mobile";
import styles from "./index.module.css";
import axios from "axios";
import Masonry, { ResponsiveMasonry } from "react-responsive-masonry";
import { useNavigate, useLocation } from "react-router-dom";

const FALLBACK_IMG = "https://via.placeholder.com/300x200?text=加载失败";

export default function Shou() {
  const [activeKey, setActiveKey] = useState("全部");
  const [list, setList] = useState([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const location = useLocation();

  //从详情页接受的搜索关键字
  const [searchKeyword, setSearchKeyword] = useState("");
  

  const navigate = useNavigate();
  const observer = useRef(null);
  const loaderRef = useRef(null);


  // 将浏览记录存储到本地
  const addToHistory = (item) => {
    // 先获取存储的数据，如果没有则使用空数组
    const storedHistory = localStorage.getItem("viewHistory");
    const history = storedHistory ? JSON.parse(storedHistory) : [];
    
    // 检查是否已存在于历史记录中
    const existingIndex = history.findIndex(historyItem => historyItem._id === item._id);
    
    if (existingIndex >= 0) {
      // 如果已存在，更新浏览时间
      history[existingIndex].viewDate = new Date().toISOString();
    } else {
      // 如果不存在，添加新记录
      history.push({
        ...item,
        viewDate: new Date().toISOString()
      });
    }
    
    // 保存回localStorage
    localStorage.setItem("viewHistory", JSON.stringify(history));
    navigate(`/detail/${item._id}`)
  }

  // 获取列表数据
  const getList = async (
    pageNum = 1,
    reset = false,
    currentTab = activeKey,
    keyword = searchKeyword
  ) => {
    if (loading) return;
    setLoading(true);

    try {
      const res = await axios.get("http://127.0.0.1:3000/list", {
        params: {
          page: pageNum,
          pageSize: 10,
          category: currentTab,
          keyword,
        },
      });

      const newData = res.data.info;

      if (activeKey !== currentTab) return;

      if (reset) {
        setList(newData);
      } else {
        setList((prev) => [...prev, ...newData]);
      }

      setHasMore(newData.length === 10);
    } catch (err) {
      Toast.show({ icon: "fail", content: "加载失败" });
    } finally {
      setTimeout(() => setLoading(false), 200); // 添加延迟防止快速切换
    }
  };
  // 搜索
  const startseo = () => {
    setPage(1);
    setHasMore(true);
    getList(1, true, activeKey, searchKeyword);
  };
  // 清空
  const clearseo = () => {
    setSearchKeyword("");
    setPage(1);
    setHasMore(true);
    getList(1, true, activeKey, "");
  };

  // 初始化或条件变化时加载第一页
  useEffect(() => {
    setPage(1);
    setHasMore(true);
    getList(1, true, activeKey, searchKeyword);
  }, [activeKey]);

  // 分页加载
  useEffect(() => {
    if (page === 1) return;
    getList(page, false, activeKey, searchKeyword);
  }, [page]);

  // 触底加载更多
  useEffect(() => {
    if (!loaderRef.current) return;
    if (observer.current) observer.current.disconnect();

    observer.current = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && hasMore && !loading) {
        setPage((prev) => prev + 1);
      }
    });

    observer.current.observe(loaderRef.current);
    return () => observer.current?.disconnect();
  }, [hasMore, loading]);

  return (
    <div className={styles.box}>
      <Card>
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <SearchBar
            placeholder="请输入内容"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e)}
            onClear={clearseo}
            style={{ flex: 1 }}
          />

          <Button size="small" color="primary" onClick={startseo}>
            搜索
          </Button>
        </div>
      </Card>

      <Tabs onChange={setActiveKey} activeKey={activeKey}>
        <Tabs.Tab title="全部" key="全部" />
        <Tabs.Tab title="日用品" key="日用品" />
        <Tabs.Tab title="玩具" key="玩具" />
        <Tabs.Tab title="学习用品" key="学习用品" />
        <Tabs.Tab title="数码宝贝" key="数码宝贝" />
      </Tabs>

      <div
        style={{
          padding: 10,
          willChange: "transform",
          backfaceVisibility: "hidden",
        }}
      >
        <ResponsiveMasonry
          columnsCountBreakPoints={{ 350: 2, 400: 2, 1024: 2 }}
        >
          <Masonry gutter="10px">
            {list.map((item) => (
              <div
                key={item._id}
                onClick={() =>{addToHistory(item)} }
                style={{
                  background: "#fff",
                  borderRadius: 6,
                  overflow: "hidden",
                  transition: "transform 0.2s",
                }}
              >
                {/* <img
                  src={item.img?.[0]?.url}
                  loading="lazy"
                  alt={item.title}
                  onError={(e) => {
                    e.target.onerror = null; // 防止循环触发
                    e.target.src = FALLBACK_IMG;
                  }}
                  style={{
                    width: "100%",
                    height: "auto",
                    display: "block",
                    objectFit: "cover",
                    backgroundColor: "#f0f0f0",
                  }}
                />  */}
                <Swiper
                  autoplay
                  loop
                  style={{ width: "100%" }}
                  indicatorProps={{
                    style: {
                      "--dot-color": "#bbb",
                      "--active-dot-color": "#1677ff",
                    },
                  }}
                >
                  {(item.img || []).map((img, index) => (
                    <Swiper.Item key={index}>
                      <img
                        src={img.url}
                        alt=""
                        loading="lazy"
                        onError={(e) => {
                          e.target.onerror = null;
                          e.target.src = FALLBACK_IMG;
                        }}
                        style={{
                          width: "100%",
                          height: "100%",
                          objectFit: "cover",
                          backgroundColor: "#f0f0f0",
                        }}
                      />
                    </Swiper.Item>
                  ))}
                </Swiper>
                <p style={{ padding: "5px 10px" }}>名称：{item.title}</p>
                <p style={{ padding: "5px 10px" }}>
                  价格：{item.price?.toFixed(2) || "未知"}
                </p>
              </div>
            ))}
          </Masonry>
        </ResponsiveMasonry>

        {loading && (
          <div style={{ textAlign: "center", padding: 10 }}>
            <SpinLoading color="primary" />
          </div>
        )}

        {!loading && !hasMore && list.length > 0 && (
          <div style={{ textAlign: "center", color: "#999", padding: 10 }}>
            没有更多内容了
          </div>
        )}

        {list.length === 0 && !loading && (
          <div style={{ textAlign: "center", color: "#999", padding: 30 }}>
            暂无数据
            <Button
              color="primary"
              size="small"
              style={{ marginTop: 10 }}
              onClick={() => {
                setPage(1);
                setHasMore(true);
                getList(1, true, activeKey, searchKeyword);
              }}
            >
              点击重试
            </Button>
          </div>
        )}

        <div ref={loaderRef} style={{ height: 1 }} />
      </div>
    </div>
  );
}
